package com.xht.service.impl;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import com.xht.constants.SystemConstants;
import com.xht.domain.ResponseResult;
import com.xht.enums.AppHttpCodeEnum;
import com.xht.exception.SystemExceptin;
import com.xht.service.UploadService;
import com.xht.utils.PathUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;


@Service
@Data
@Component
@ConfigurationProperties(prefix = "oss")
public class OSSUploadServiceImpl implements UploadService {

    //七牛云OSS里面的 密钥 和 库,具体数据在配置文件中
    private String accessKey;
    private String secretKey;
    private String bucket;

    @Override
    public ResponseResult uploadImg(MultipartFile img) {

        //判断文件的类型
        String originalFilename = img.getOriginalFilename();
        if (originalFilename == null || (!originalFilename.endsWith(".jpg") && !originalFilename.endsWith(".png"))) {
            throw new SystemExceptin(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }

        String filePath = PathUtils.generateFilePath(originalFilename);

        String url = uploadOSS(img, filePath);

        return ResponseResult.okResult(url);
    }

    @Override
    public ResponseResult uploadVideo(MultipartFile file) throws IOException {
        //判断文件类型
        String originalFilename = file.getOriginalFilename();
        //如果不是视频文件,就抛异常
        if (originalFilename == null || (!originalFilename.endsWith(".mp4") && !originalFilename.endsWith(".avi"))) {
            throw new SystemExceptin(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }

        String filePath = PathUtils.generateFilePath(originalFilename);
        String url = uploadOSSVedio(file, filePath);

        return ResponseResult.okResult(url);
    }

    //上传图片时 获取 url
    public String uploadOSS(MultipartFile img, String filePath) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
//        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
////...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
//        String accessKey = "your access key";
//        String secretKey = "your secret key";
//        String bucket = "your bucket name";

//默认不指定key的情况下，以文件内容的hash值作为文件名

        //文件名
        String key = filePath;

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);

            //将图片img 转化为 流 的形式
            InputStream inputStream = img.getInputStream();

            //创建一个凭证
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return SystemConstants.DOMAIN_ADDRESS + key; //访问图片路径 为 域名地址 + 文件名 (注:域名只有一个月有效期)
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);

                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
                return "七牛云的问题导致上传失败";
            }
        } catch (Exception ex) {

            //ignore
            return "其他异常问题导致上传失败";
        }

    }

    //上传视频
    public String uploadOSSVedio(MultipartFile file, String filePath) throws IOException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
////...其他参数参考类注释
// 设置分片上传的临时目录
        String localTempDir = System.getProperty("java.io.tmpdir");
        FileRecorder fileRecorder = new FileRecorder(localTempDir);
        UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
//...生成上传凭证，然后准备上传
//        String accessKey = "your access key";
//        String secretKey = "your secret key";
//        String bucket = "your bucket name";

//默认不指定key的情况下，以文件内容的hash值作为文件名

        //文件名
        String key = filePath;

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);

            //将图片img 转化为 流 的形式
            InputStream inputStream = file.getInputStream();

            //创建一个凭证
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return SystemConstants.DOMAIN_ADDRESS + key; //访问图片路径 为 域名地址 + 文件名 (注:域名只有一个月有效期)
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);

                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
                return "七牛云的问题导致上传失败";
            }
        } catch (Exception ex) {

            //ignore
            return "其他异常问题导致上传失败";
        }

    }
}
